#include "mgallery.h"
#include "AEEAppGen.h"
#include "dfon_comdef.h"

typedef struct 
{
	AEEApplet a;
	MGallery *instance;
} MApplet ;

static void FreeHandler(IApplet *data)
{
	MApplet *me = (MApplet *)data;
	MGallery_Destroy(me->instance);
	me->instance = NULL;
}

static boolean HandleEvent(void *data, AEEEvent evt, uint16 wParam, uint32 dwParam)
{
	MApplet *me = data;
	IAppHistory *appHistory = NULL;

	switch(evt)
	{
	case EVT_APP_START:
		return MGallery_OnStart(me->instance, (AEEAppStart*)dwParam);

	case EVT_APP_STOP:
		return TRUE;

	case EVT_APP_SUSPEND:
		if(wParam == AEE_SUSPEND_NORMAL){
			ISHELL_CreateInstance(me->a.m_pIShell, AEECLSID_APPHISTORY, (void**)&appHistory);
			if(appHistory){
				IAPPHISTORY_SetResumeData(appHistory, &me->instance, sizeof(me->instance));
			}
			RELEASEIF(appHistory);
		}else if(wParam == AEE_SUSPEND_CLOSE){
			MGallery_Destroy(me->instance);
			me->instance = NULL;
		}
		break;

	case EVT_APP_RESUME:
		ISHELL_CreateInstance(me->a.m_pIShell, AEECLSID_APPHISTORY, (void**)&appHistory);
		if(appHistory){
			int size = sizeof(me->instance);
			me->instance = NULL;
			IAPPHISTORY_GetResumeData(appHistory, &me->instance, &size);
			if(me->instance == NULL){
				me->instance = MGallery_Create(me->a.m_pIShell);
				return MGallery_OnStart(me->instance, (AEEAppStart*)dwParam);
			}
		}
		RELEASEIF(appHistory);
		break;

	case EVT_KEYGUARD:
		return TRUE;
	}

	if(me->instance && MGallery_HandleEvent(me->instance, evt, wParam, dwParam))
		return TRUE;

	if(evt == EVT_APP_RESUME || evt == EVT_APP_SUSPEND)
		return TRUE;

	return FALSE;
}

int AEEClsCreateInstance(AEECLSID ClsId,IShell * pIShell,IModule * pMod,void ** ppObj)
{
	*ppObj = NULL;
	
	if(AEEApplet_New(sizeof(MApplet), ClsId, pIShell, pMod, (IApplet**)ppObj, HandleEvent, FreeHandler))
	{
		MApplet *me = *ppObj;
		me->instance = MGallery_Create(me->a.m_pIShell);
		if(me->instance)
			return AEE_SUCCESS;
		else
			return EFAILED;
	}
	
	return EFAILED;
}